/**------------------------------------------------------------------------/
# JOOMLAVI Script
# @version		1.0.1
# -------------------------------------------------------------------------/
# author    Open Source Code Solutions Co
# copyright Copyright (C) 2011 joomlavi.com. All Rights Reserved.
# @license - http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL or later.
# Websites: http://www.joomlavi.com
# Technical Support:  http://www.joomlavi.com/my-tickets.html
/*-------------------------------------------------------------------------*/


(function(window){
	var check = function(name){
		var vs = name.split(/,/g);
		for(var i = 0; i < vs.length; i++) if((function(name){
			var 
				ns = name.split(/\./g),
				root = window
			;
			for(var x =0 ; x < ns.length; x ++){
				if(!root[ns[x]]) return false;
				root = ns[x];
			}
		})(vs[i]) === false) return false;
		return true;
	}
	
	var 
		waitObjs = {},
		id = 0
	;
	
	var wait = function(name,success){
		if(typeof success !== 'function') return;
	
		var fn = function(){
			try{
				success();
				change();
			}catch(e){
				if(require.breakOnError) throw e;
				console.log(e);
			}
		}
	
		if(check(name)) fn();
		else {
			waitObjs[name] = waitObjs[name] || [];
			waitObjs[name].push(fn);
		} 
	}
	
	var change = function(){
		for(var x in waitObjs){
			if( check(x)){
				var fns = waitObjs[x];
				delete waitObjs[x];
				for(var i in fns){
					fns[i]();
				}
			}
		}
	}
	
	
	var head;
	var load = function(url){
		
		var script = document.createElement('script');
		var onload = function(){
			script.onload = null;
			//script.onreadystatechange = null;
			change();
			script.id = null;
		}
		script.id = 'JVLoadScript_'  + id ++;
		
		script.src = url;
		script.type = 'text/javascript';
		(head || (head = document.getElementsByTagName('head')[0]));
		document.write(script.outerHTML);
		script = document.getElementById(script.id);
		script.onload = onload;
		script.onreadystatechange = function(){
			if((script.readyState == 'loaded' && document.documentMode < 10) || script.readyState == 'complete'){
				onload();
			}
		}
	}
	
	window.require = function(name,url,success){
		wait(name,success);
		if(!check(name)) load(url);
	}
	require.load = load;
	require.check = check;
	require.wait = wait;
	require.breakOnError = true;
})(window);